package com.example.controller;

import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.ManagementService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.runtime.Job;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @Deacription TODO
 * @Author baohuajie
 * @Date 2021/1/16 8:12
 * @Version 1.0
 **/
@RestController
@RequestMapping("/activiti")
@Slf4j
public class ActivitiController {

    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
    @Autowired
    private TaskService taskService;
    @Autowired
    private ManagementService managementService;

    @RequestMapping("/deployProcess")
    public String deployProcess(@RequestParam("name")String name) {
        log.info("部署工作流start");
        repositoryService.createDeployment().addClasspathResource(name)
                .name(name)
                .key(name)
                .deploy();
        log.info("部署工作流end");


        List<ProcessDefinition> list = repositoryService.createProcessDefinitionQuery().active().orderByDeploymentId().desc().list();
        for (ProcessDefinition processDefinition : list) {
            log.info("id:{}", processDefinition.getId());
        }
        List<ProcessDefinition> list1 = repositoryService.createProcessDefinitionQuery().active().orderByDeploymentId().desc().list();
        return "OK";
    }

    @RequestMapping("/startProcess")
    public String startProcess(@RequestParam("name")String name) {
        log.info("startProcess start");
        Map<String, Object> variables = new HashMap<>();
        String businessKey = UUID.randomUUID().toString();
        variables.put("businessKey", businessKey);
        threadPoolTaskExecutor.execute(new Runnable() {
            @Override
            public void run() {
                ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(name, businessKey, variables);
                log.info("startProcess end, processInstanceId", processInstance.getProcessInstanceId());
            }
        });

        return "OK";
    }

    @RequestMapping("/deleteProcess")
    public String deleteProcess() {
        log.info("deleteProcess start");
        List<Execution> list = runtimeService.createExecutionQuery().list();
        List<ProcessInstance> processInstances = runtimeService.createProcessInstanceQuery().list();
        for (ProcessInstance processInstance : processInstances) {
            String processInstanceId = processInstance.getProcessInstanceId();
            try {
                runtimeService.deleteProcessInstance(processInstanceId, "临时删除");
            } catch (Exception e) {
                log.info("deleteProcess 异常");
            }
            log.info("deleteProcess end, processInstanceId:{}", processInstanceId);
        }
        log.info("deleteProcess end");
        return "OK";
    }

    @RequestMapping("/retryProcess")
    public String retryProcess() {
        log.info("retryProcess start");
        List<Job> list = managementService.createDeadLetterJobQuery().list();
        for (Job job : list) {
            String jobId = job.getId();
            Job job1 = managementService.moveDeadLetterJobToExecutableJob(jobId, 2);
        }
        return "OK";
    }

    @RequestMapping("/completeTask")
    public String completeTask() {
        log.info("completeTask start");
        List<ProcessInstance> processInstanceList = runtimeService.createProcessInstanceQuery().list();
        List<Task> taskList = taskService.createTaskQuery().active().list();
        taskList.forEach(task -> {
            String taskId = task.getId();
            System.out.println(taskId);
            taskService.complete(taskId);
        });
        return "OK";
    }

}
